package com.kevin.designpattern.factory_method.config_factory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class CoffeeFactory {


    // 加载配置文件，获取配置文件中全类名，创建存储

    // 1.定义容器对象存储对象
    private static HashMap<String, Coffee> map = new HashMap<>();

    //2.加载配置文件，并创建配置文件全类名的对象进行存储

    static {
        // 创建对象
        Properties p = new Properties();

        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            p.load(is);
            // 获取全类名创建对象
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                String className = p.getProperty((String) key);
                // 反射创建对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.getDeclaredConstructor().newInstance(null);
                map.put((String) key, coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Coffee createCoffee(String name) {

        Coffee coffee = map.get(name);
        return coffee;
    }
}
